package com.suisung.shopsuite.common.config;

import com.suisung.shopsuite.common.config.resolver.UnderlineToCamelArgumentResolver;
import com.suisung.shopsuite.common.consts.ConstantJwt;
import com.suisung.shopsuite.sys.service.ConfigBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.Resource;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.suisung.shopsuite.common.utils.UploadUtil.getUploadBaseDir;

/**
 * WebMvc配置, 拦截器、资源映射等都在此配置
 *
 * @author Xinze
 * @since 2019-06-12 10:11:16
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Lazy
    @javax.annotation.Resource
    private ConfigBaseService configBaseService;

    /**
     * 支持跨域访问
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedHeaders("*")
                .exposedHeaders(ConstantJwt.TOKEN_HEADER_NAME)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
                .allowCredentials(true)
                .maxAge(3600);
    }

    /**
     * 添加参数解析器
     *
     * @param argumentResolvers 参数解析器
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new UnderlineToCamelArgumentResolver());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 统一处理路径分隔符，兼容不同操作系统
        String formattedPath = getUploadBaseDir().replace("/", File.separator)
                .replace("\\", File.separator);

        // 确保路径以分隔符结尾
        if (!formattedPath.endsWith(File.separator)) {
            formattedPath += File.separator;
        }

        Integer uploadType = configBaseService.getConfig("upload_type", 0);
        if (uploadType != 0) {
            return ;
        }

        registry.addResourceHandler("/front/sys/upload/**")
                .addResourceLocations("file:" + formattedPath)
                .setCachePeriod(3600)
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        Resource requestedResource = location.createRelative(resourcePath);
                        return requestedResource.exists() && requestedResource.isReadable()
                                ? requestedResource
                                : null;
                    }
                });
    }
}
